package io.hepu.robotize.security;

import io.hepu.robotize.IContext;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Shiro过滤器，拥有指定权限的用户才能访问受保护资源
 */
public class JwtAuthzFilter extends PermissionsAuthorizationFilter {
    private static final Logger LOG = LoggerFactory.getLogger(JwtAuthzFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        LOG.info("Authorization ==> Denied: {}", IContext.getRequest().getRequestURL());
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated()) {
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN, "用户无相关权限");
        }
        return false;
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        LOG.debug("Authorization ==> Allowed: {}", IContext.getRequest().getRequestURL());
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
